﻿using Dapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Npgsql;
using System;
using System.Collections.Generic;
using housingsafety.server.Entities;

namespace housingsafety.server.Helpers
{
    public class FlywayDatabase
    {
        public static void MigrateDatabase(ZmDbContext dataContext, IWebHostEnvironment env, ILogger<Startup> logger)
        {
            //dataContext.Database.Migrate();

            // exclude db/datasets from production and staging environments
            string location = env.IsDevelopment() ? "db" : "db/migrations";

            try
            {
                System.Data.Common.DbConnection dbConnection = dataContext.Database.GetDbConnection();

                // PG 不支持is not exists
                // CREATE DATABASE zealmap WITH OWNER = postgres ENCODING = 'UTF8' LC_COLLATE = 'C' LC_CTYPE = 'C' TABLESPACE = pg_default CONNECTION LIMIT = -1;

                //var npgsqlConnectionStringBuilder = new NpgsqlConnectionStringBuilder(dbConnection.ConnectionString);
                //npgsqlConnectionStringBuilder.Database = null;

                //var npgsqlConnection = new NpgsqlConnection(npgsqlConnectionStringBuilder.ConnectionString);
                //npgsqlConnection.Execute($"CREATE DATABASE IF NOT EXISTS `{dbConnection.Database}` DEFAULT CHARACTER SET utf8mb4;");
                //npgsqlConnection.Close();
                //npgsqlConnection.Dispose();

                var evolve = new Evolve.Evolve(dbConnection, msg => logger.LogInformation(msg))
                {
                    MetadataTableSchema = dbConnection.Database,
                    MetadataTableName = "zm_db_changelog",
                    Locations = new[] { location },
                    IsEraseDisabled = true,
                    Placeholders = new Dictionary<string, string>
                    {
                        ["${table4}"] = "table4"
                    }
                };

                //evolve.Migrate();
            }
            catch (Exception ex)
            {
                logger.LogError("Database is not exitst or Database migration failed.", ex);
                throw;
            }
        }
    }
}
